import collections


class Solution(object):
    def bestTeamScore(self, scores, ages):
        n = len(scores)
        t = [[ages[i], scores[i]] for i in range(n)]
        t.sort(reverse=True)
        t = [p[1] for p in t]
        d = collections.defaultdict(int)
        d[t[0]] = t[0]
        for num in t[1:]:
            next_d = collections.defaultdict(int)
            next_d[num] = num
            for key in d:
                next_d[key] = max(next_d[key], d[key])
                if num <= key:
                    next_d[num] = max(next_d[num], d[key] + num)
            d = next_d
        return max(d.values())


data = Solution()
scores = [4, 5, 6, 5]
ages = [2, 1, 2, 1]
print(data.bestTeamScore(scores, ages))
